import { getPathList, Marker } from "@/api";
import { Map } from "ol";
import Feature from "ol/Feature";
import LineString from "ol/geom/LineString";
import VectorLayer from "ol/layer/Vector";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import { useEffect, useState } from "react"
import { pathStyle } from "./util";

interface Props {
  map: Map
}

const TrackCheckbox: React.FC<Props> = ({ map }) => {

  const [checked, setChecked] = useState(true)
  const [pathList, setPathList] = useState<Marker[]>([])

  // 轨迹数据获取
  useEffect(() => {
    async function main() {
      const data = await getPathList()
      setPathList(data)
    }
    if (checked) {
      main()
    }
  }, [checked]);

  // 轨迹控制
  useEffect(() => {

    if (checked) {

      const pathCoordinates = pathList.map(item => fromLonLat([item.lng, item.lat])); // 将经纬度转换为OpenLayers的坐标系

      const pathGeometry = new LineString(pathCoordinates);

      const vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [new Feature({
            geometry: pathGeometry, // 设置路径的几何数据
          })],
        }),
        style: pathStyle
      });

      map.addLayer(vectorLayer)


      return () => {
        map.removeLayer(vectorLayer)
      }
    }
  }, [checked, map, pathList]);

  return (
    <input
      className="toggle toggle-sm"
      type="checkbox"
      checked={checked}
      onChange={(e) => setChecked(e.target.checked)}
    />
  )
}

export default TrackCheckbox